package de.tum.team26.eistpoll.client.UI;

import java.util.LinkedList;

import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.tum.team26.eistpoll.client.EIST_POLL;
import de.tum.team26.eistpoll.shared.PollData;

/**
 * Class to display to the Result
 */
public class Results extends UIElement{

	// Controller
	EIST_POLL controller;
	
	// Variables
	boolean isLecturer;
	Result poll[];
	VerticalPanel resultsPanel = new VerticalPanel();
	
	// UI Elements
	Label lblErrMsg;
	
	/**
	 * Initialise
	 * @param isLecturer
	 * @param controller
	 */
	public Results(boolean isLecturer, EIST_POLL controller){
		this.controller = controller;
		this.isLecturer = isLecturer;
		
		controller.getResults(isLecturer);
	}

	public void updateResults(LinkedList<PollData> result){
		// not yet initialized
		if (poll != null){
			for (int i=0; i<poll.length; i++){
				resultsPanel.remove(poll[i].getContainer());	// clear old Polls
			}
		}
		
		if ((result == null) || (result.isEmpty())){
			return;
		}
		
		poll = new Result[result.size()]; // init Array
		
		int i = 0;
		for (PollData e : result) {
			poll[i] = new Result(controller, e.getId(), e.getTitle(), isLecturer, e.isActive());
			if (isLecturer) poll[i].updateResults(e.getOption(), e.getLike(), e.getDisLike());
			else poll[i].updateResults(e.getOption());
			resultsPanel.add(poll[i].getContainer());
			i++;
		}

	}
	
	// As always
	
	@Override
	public VerticalPanel getContainer() {
		return resultsPanel;
	}

	@Override
	public void displayErrorMessage(String message) {
		if (lblErrMsg == null){
			lblErrMsg = new Label(message);
			lblErrMsg.setStyleName("error");
			resultsPanel.add(lblErrMsg);
		}
		else{
			lblErrMsg.setText(message);
		}
		
	}

}
